package com.qf.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @Description: 公用常量
 * @Data: 2022/9/1 11:51
 * @Pacakge: com.qf.utils
 * @ClassName: ConnectionUtils
 * @Author: fan
 */
@Component("connectionUtils")
public class ConnectionUtils {
    private ThreadLocal<Connection> t1= new ThreadLocal<>();
    @Autowired
    private DataSource dataSource;
    public Connection getConnection(){
        try {
            Connection connection = t1.get();
            if (connection == null){
                connection = dataSource.getConnection();
                t1.set(connection);
            }
            return connection;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    public void removeConnection(){
        t1.remove();
    }
}
